package com.eastfair.messagecenter.handler.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.messagecenter.domain.sms.SmsParam;
import com.eastfair.messagecenter.domain.TaskInfo;
import com.eastfair.messagecenter.domain.sms.SmsRecord;
import com.eastfair.messagecenter.entity.Msg;
import com.eastfair.messagecenter.entity.SmsTemplate;
import com.eastfair.messagecenter.enumeration.ChannelType;
import com.eastfair.messagecenter.enumeration.SendStatus;
import com.eastfair.messagecenter.handler.BaseHandler;
import com.eastfair.messagecenter.handler.Handler;
import com.eastfair.messagecenter.model.SmsContentModel;
import com.eastfair.messagecenter.script.sms.SmsScriptHolder;
import com.eastfair.messagecenter.service.MsgService;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

/**
 * 短信发送处理
 *
 * @author ligang
 */
@Component
@Slf4j
public class SmsHandler extends BaseHandler implements Handler {

    @Autowired
    private MsgService msgService;

    public SmsHandler() {
        channelType = ChannelType.SMS;
    }

    @Autowired
    private SmsScriptHolder smsScriptHolder;

    @Value("${com.eastfair.smsHanler}")
    private String smsHanler;

    @Override
    public boolean handler(TaskInfo taskInfo) {
        SmsParam smsParam = SmsParam.builder()
                .mobiles(new HashSet<>(taskInfo.getMobiles()))
                .content(getSmsContent(taskInfo))
                .msgIds(taskInfo.getMsgIds())
                .build();
        try {
            /**
             * 1、动态配置做流量负载
             * 2、发送短信
             */
            //暂时写死服务商
//            String scriptName="QyxsSmsScript";
//            String scriptName="XmSmsScript";

            String scriptName = smsHanler;
            log.info("使用的短信服务商是{}", scriptName);
            List<SmsRecord> recordList = smsScriptHolder.route(scriptName).send(smsParam);
            log.info("短信服务商发送结果:{}", JSON.toJSONString(recordList));
//            List<SmsRecord> recordList = smsScriptHolder.route("XmSmsScript").send(smsParam);
            if (CollUtil.isNotEmpty(recordList)) {
                //保存到消息表里
                SmsRecord smsRecord = recordList.get(0);
                List<Msg> msgList = msgService.list(null, recordList.get(0).getMsgIds());
                log.info("查询msg集合:{}", JSON.toJSONString(msgList));
                if (CollectionUtil.isNotEmpty(msgList)) {
                    for (Msg msg : msgList) {
                        msg.setIsNoteSendSucc(smsRecord.getIsSuccess() == true ? BusinessConstant.YES : BusinessConstant.NO);
                        msg.setContent(smsRecord.getMsgContent());
                        msg.setSendTime(LocalDateTime.now());
                        msg.setIsSendNow(BusinessConstant.YES);
                        msg.setSendStatus(smsRecord.getIsSuccess() == true ? SendStatus.SEND_SUCC : SendStatus.SEND_FAIL);
                        msg.setNoteSendResult(smsRecord.getReportContent());
                    }
                    msgService.updateBatchById(msgList);
                }
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("SmsHandler#handler fail:{},params:{}",
                    Throwables.getStackTraceAsString(e), JSON.toJSONString(smsParam));
        }
        return false;
    }


    /**
     * 如果有输入链接，则把链接拼在文案后
     * <p>
     * PS: 这里可以考虑将链接 转 短链
     * PS: 如果是营销类的短信，需考虑拼接 回TD退订 之类的文案
     */
    private String getSmsContent(TaskInfo taskInfo) {
        SmsContentModel smsContentModel = (SmsContentModel) taskInfo.getContentModel();
        if (StrUtil.isNotBlank(smsContentModel.getUrl())) {
            return smsContentModel.getContent() + " " + smsContentModel.getUrl();
        } else {
            return smsContentModel.getContent();
        }
    }

    @Override
    public void recall(SmsTemplate smsTemplate) {

    }
}
